package com.ey12.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import com.ey12.file.DBPoolFactory;
import com.ey12.utils.DateUtil;
import java.util.Timer;

public class TimerService extends HttpServlet implements ServletContextListener {

	private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
	private static String URL = "";
	private static String USN = "";
	private static String PWD = "";
	private static int timerInterval = 3;
	private static int checkInterval = 24;
	private static int quickInterval = 3;
	
	private static Timer timer;

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

	}

	public void contextInitialized(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
	
//		DBPoolFactory.initSmartPoolFactory();
		
		URL = sc.getInitParameter("DbUrl");
		USN = sc.getInitParameter("DbUsername");
		PWD = sc.getInitParameter("DbPwd");
		if ("".equals(DBPoolFactory.URL)) {
			DBPoolFactory.URL = URL;
		}
		if ("".equals(DBPoolFactory.USN)) {
			DBPoolFactory.USN = USN;
		}
		if ("".equals(DBPoolFactory.PWD)) {
			DBPoolFactory.PWD = PWD;
		}
		
		timerInterval =Integer.parseInt(sc.getInitParameter("TimerInterval"));		
		checkInterval = Integer.parseInt(sc.getInitParameter("CheckInterval"));
		quickInterval = Integer.parseInt(sc.getInitParameter("QuickInterval"));
		timer = new Timer(true);
		timer.schedule(new CheckTask(checkInterval,quickInterval,URL,USN,PWD), 0, timerInterval*60* 1000);//
		
		System.out.println("[" + new DateUtil().toTimeString()
				+ "] The timer is starting...");
		System.out.println("[" + new DateUtil().toTimeString()
				+ "] URL="+URL);
		System.out.println("[" + new DateUtil().toTimeString()
				+ "] USN="+USN+" PWD="+PWD);
	}

	public void contextDestroyed(ServletContextEvent sce) {

		System.out.println("[" + new DateUtil().toTimeString()
				+ "] The timer is closing...");

	}

}
